﻿using System;
using UFIDA.U9.CBO.FI.Enums;
using UFIDA.U9.SM.Ship;
using UFSoft.UBF.Business;
using UFSoft.UBF.Eventing;

namespace UFIDA.U9.CusDev.QJKJPlugInBE
{
    class ProcessForARSaveNum : IEventSubscriber
    {
        public void Notify(params object[] args)
        {

            if (args == null || args.Length == 0 || !(args[0] is UFSoft.UBF.Business.EntityEvent)) return;
            BusinessEntity.EntityKey key = ((UFSoft.UBF.Business.EntityEvent)args[0]).EntityKey;

            if (key == null || key.GetEntity() == null) return;
            //应收单
            UFIDA.U9.AR.ARBill.ARBillHead ar = key.GetEntity() as UFIDA.U9.AR.ARBill.ARBillHead;
            if (ar == null) return;

            #region 应收单保存时,判断 开票数量<=出货数量-退货数量
            if (ar.OriginalData.DocStatus == BillStatusEnum.Opened && ar.DocStatus == BillStatusEnum.Approving)
            {
                foreach (var line in ar.ARBillLines)
                {
                    Ship ship = Ship.Finder.Find($"DocNo='{line.SrcBillNum}'");
                    if (ship == null) continue;
                    foreach (var shipLine in ship.ShipLines)
                    {
                        //判断来源行号与出货行好一致
                        if (int.Parse(line.SrcBillLineNum) == shipLine.DocLineNo)
                        {
                            //判断出货单 : 开票数量 <= 出货数量 - 退货数量
                            // if (shipLine.TotalAccountQtyPriceAmount <= shipLine.ShipQtyInvAmount - shipLine.RMRUseQtyTUAmount)
                            if (line.PUAmount <= shipLine.ShipQtyInvAmount - shipLine.RMRUseQtyTUAmount)
                            {
                                break;
                            }
                            else
                            {
                                // throw new Exception($"[{line.LineNum}]行累计开票数量[{Math.Round(shipLine.TotalAccountQtyPriceAmount, 2)}] > 出货数量[{Math.Round(shipLine.ShipQtyInvAmount,2)}] - 退货数量[{Math.Round(shipLine.RMRUseQtyTUAmount,2)}]");
                                throw new Exception($"[{line.LineNum}]行累计开票数量[{Math.Round(line.PUAmount, 2)}] > 出货数量[{Math.Round(shipLine.ShipQtyInvAmount, 2)}] - 退货数量[{Math.Round(shipLine.RMRUseQtyTUAmount, 2)}]");

                            }
                        }

                    }


                }

            }
           
           



            #endregion

        }

    }
}
